package com.dsg.service.apply.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.CollectionUtil;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.entity.apply.DsgApplyDiscount;
import com.dsg.dao.apply.DsgApplyDiscountMapper;
import com.dsg.entity.dto.CardDiscountDto;
import com.dsg.service.apply.IDsgApplyDiscountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 折扣資料 服务实现类
 * </p>
 *
 * @author system
 * @since 2020-07-10
 */
@Service
public class DsgApplyDiscountServiceImpl extends ServiceImpl<DsgApplyDiscountMapper, DsgApplyDiscount> implements IDsgApplyDiscountService {
    @Override
    public List<CardDiscountDto> cardDiscount(String cardOids, String effDateBegin, String effDateEnd) {
        return baseMapper.cardDiscount(cardOids, effDateBegin, effDateEnd);
    }

    @Override
    public void saveDiscount(String cusNo, List<DsgApplyDiscount> applyDiscountList) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("OID");
        wrapper.eq("CUS_NO", cusNo);
        wrapper.eq("DIS_TARGET", DsgApplyDiscount.DIS_TARGET_CUS);
        List<DsgApplyDiscount> preDiscountList = list(wrapper);
        List<String> preOids = null;
        List<String> oids = null;
        if (CollectionUtil.isNotEmpty(preDiscountList)) {
            preOids = preDiscountList.stream().map(DsgApplyDiscount::getOid).collect(Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(applyDiscountList)) {
            oids = applyDiscountList.stream().map(DsgApplyDiscount::getOid).collect(Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(preOids) && CollectionUtil.isNotEmpty(oids)) {
            preOids.removeAll(oids);
        }

        if (CollectionUtil.isNotEmpty(preOids)) {
            removeByIds(preOids);
        }

        for (DsgApplyDiscount discount :
                applyDiscountList) {
            if (StringUtil.isEmpty(discount.getOid())) {
                discount.setCusNo(cusNo);
                discount.setOid(UUIDGenerator.getUUID());
                discount.setDisTarget(DsgApplyDiscount.DIS_TARGET_CUS);
            }
        }
        saveOrUpdateBatch(applyDiscountList);
    }

}
